<template>
  <div class="search-suggestion">
    <van-cell icon="search" v-for="(text, index) in suggestion" :key="index">
      <div
        slot="title"
        v-html="highLight(text)"
        @click="$emit('search', text)"
      ></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/search'

import { debounce } from 'lodash'
export default {
  name: 'SearchSuggestion',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      suggestion: [],
    }
  },
  computed: {},
  watch: {
    searchText: {
      // handler(val) {
      //   // console.log(val)
      //   this.loadSearchSuggestion(val)
      // },

      handler: debounce(function (val) {
        this.loadSearchSuggestion(val)
      }, 400),
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    async loadSearchSuggestion(val) {
      try {
        const { data } = await getSearchSuggestions(val)
        console.log(data)
        this.suggestion = data.data.options
      } catch (err) {
        this.$toast('获取数据失败,请稍后重试')
      }
    },
    highLight(text) {
      const reg = new RegExp(this.searchText, 'gi')
      return text.replace(
        reg,
        `<span style="color:red">${this.searchText}</span>`
      )
    },
  },
}
</script>

<style scoped lang="less"></style>